<template>
  <div>
    <el-tree
      ref="tree"
      :data="permission"
      :props="{label:'name'}"
      default-expand-all
      show-checkbox
      check-strictly
      node-key="id"
    />
    <div class="footer">
      <el-button size="small" @click="$emit('close')">取消</el-button>
      <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionsList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { assignPermIds, AssignRoles } from '@/api/roles'

export default {
  name: 'AppIndex',

  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permission: []
    }
  },

  watch: {},
  created() {
    // 获取全部权限列表
    this.loadPermission()
    // 获取所有角色权限
    this.loadRolesPerm()
  },

  methods: {
    async loadPermission() {
      try {
        const res = await getPermissionsList()
        this.permission = tranListToTreeData(res.data)
      } catch (e) {
        console.log(e)
      }
    },
    async hSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      // console.log(id)
      try {
        const res = await assignPermIds({ id: this.id, permIds })
        this.$message.success(res.message)
        this.$emit('close')
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 获取角色权限并回填
    async loadRolesPerm() {
      try {
        const res = await AssignRoles(this.id)
        // console.log(res)
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (e) {
        console.log(e)
      }
    }
  }
}

</script>

<style lang="scss" scoped>
// .footer{
//   display: flex;
//   justify-content: end;
// }
</style>
